package com.clgk.wechatmall.common.excel;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.jxls.transformer.XLSTransformer;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class ExcelExportUtils
{
  public static void exportExcelByTemplate(String fileName, String templatePath, Map<String, Object> dataMap, HttpServletRequest request, HttpServletResponse response)
    throws Exception
  {
    String agent = request.getHeader("User-Agent");
    boolean isMSIE = (agent != null) && (agent.indexOf("MSIE") != -1);
    if (isMSIE) {
      fileName = URLEncoder.encode(fileName, "UTF8");
    } else {
      fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
    }
    response.setContentType("octets/stream");
    response.addHeader("Content-Disposition", "attachment;filename=" + fileName + ".xls");
    
    InputStream xlsTemplateIO = null;
    ServletOutputStream sos = null;
    try
    {
      XLSTransformer transformer = new XLSTransformer();
      URL url = FilePathUtils.locateFromClasspath(templatePath);
      File templateFile = FilePathUtils.fileFromURL(url);
      xlsTemplateIO = new FileInputStream(templateFile);
      
      HSSFWorkbook workbook = (HSSFWorkbook)transformer.transformXLS(xlsTemplateIO, dataMap);
      

      workbook.write(sos = response.getOutputStream());
      sos.flush();
      if (null != sos) {
        try
        {
          sos.close();
        }
        catch (IOException e)
        {
          sos = null;
        }
      }
      if (null != xlsTemplateIO) {
        try
        {
          xlsTemplateIO.close();
        }
        catch (IOException e)
        {
          xlsTemplateIO = null;
        }
      }
      return;
    }
    catch (Exception e)
    {
      throw e;
    }
    finally
    {
      if (null != sos) {
        try
        {
          sos.close();
        }
        catch (IOException e)
        {
          sos = null;
        }
      }
      if (null != xlsTemplateIO) {
        try
        {
          xlsTemplateIO.close();
        }
        catch (IOException e)
        {
          xlsTemplateIO = null;
        }
      }
    }
  }
}
